<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect,
  useMessage,
  NFlex,
  NAvatar,
  NSelect, NUpload,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import { getToken } from '@/utils'
import { formatDate, renderIcon } from '@/utils'
import { useCRUD } from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'

const model_name = "耗材使用明细"

defineOptions({ name: model_name })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE
import default_image from '@/assets/images/mz.jpg'

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: model_name,
  initForm: {
    interval:30
  },
  doCreate: api.createConsumablesUse,
  doUpdate: api.updateConsumablesUse,
  doDelete: api.deleteConsumablesUse,
  refresh: () => $table.value?.handlerefresh(),
})
const data = reactive({
  token: getToken(),
  uploadAction: base_path+'api/appointment/project/file',
  deptOption: [],
  gotypeData: [],
  InstiumentData: [],
  ProjectData: [],
  upload: null,
  fileListLength: 0,
  goods:[]
})
onMounted(() => {
  api.getConsumablesType().then((res) => (data.gotypeData = res.data))
  $table.value?.handleSearch()
})

//上传封面图
const message = useMessage();
const customRequestMethod = (options) => {
  const { file } = options.file;
  const formData = new FormData();
  formData.append('file', file);
  fetch(data.uploadAction, {
    method: 'POST',
    headers: options.headers,
    body: formData,
  })
      .then((response) => response.json())
      .then((data) => {
        console.log(data, 'datatat');
        if (data.code === 200) {
          modalForm.value.cover = data.data.url
          message.success('封面图上传成功');
          options.onProgress(data);
        }else{
          message.error(data.msg);
        }
      })
}

const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  if (data.code === 200) {
    file.url = data.data.url
    message.success('上传成功')
  } else {
    message.error(data.data)
  }

  return file
}


function  level_format(level,data){
  let ret = ""
  if (data) {
    data.forEach((item) => {
    if(item.value === level){
      ret = item.label
    }
  })
  }
  
  return ret
}
const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '门店',
    key: 'space_name',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '耗材名称',
    key: 'consumables_name',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '使用数量',
    key: 'nums',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
     {
    title: '病例编号',
    key: 'cases_id',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  //    {
  //   title: '订单编号',
  //   key: 'order_id',
  //   width: 60,
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  // },
     {
    title: '划扣人',
    key: 'user_name',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  //    {
  //   title: '划扣商品',
  //   key: 'goods_name',
  //   width: 60,
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  // }, {
  //   title: '划扣次数',
  //   key: 'buckling_nums',
  //   width: 60,
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  // },
     {
    title: '划扣时间',
    key: 'created_at',
    width: 60,
    align: 'center',
    ellipsis: { tooltip: true },
  },

  {
    title: '操作',
    key: 'actions',
    width: 80,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                handleEdit(row)
              },
            },
            {
              default: () => '编辑',
              icon: renderIcon('material-symbols:edit', { size: 16 }),
            }
          ),
          [[vPermission, 'post/api/content/contents/update']]
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete({ data_id: row.id }, false),
            onNegativeClick: () => {},
          },
          {
            trigger: () =>
              withDirectives(
                h(
                  NButton,
                  {
                    size: 'small',
                    type: 'error',
                  },
                  {
                    default: () => '删除',
                    icon: renderIcon('material-symbols:delete-outline', { size: 16 }),
                  }
                ),
                [[vPermission, 'delete/api/content/contents/delete']]
              ),
            default: () => h('div', {}, '确定删除该数据吗?'),
          }
        ),
      ]
    },
  },
]

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

</script>

<template>

      <CommonPage show-footer :title="model_name">
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getConsumablesUse"
          :scroll-x="1200"
        >
          <template #queryBar>
            <QueryBarItem label="名称" :label-width="40">
              <NInput
                v-model:value="queryItems.name"
                clearable
                type="text"
                placeholder="请输入名称"
                @keypress.enter="$table?.handleSearch()"
              />
            </QueryBarItem>
            <QueryBarItem label="录入时间" :label-width="70">
          <NDatePicker
              v-model:value="datetimeRange"
              type="datetimerange"
              clearable
              placeholder="请选择时间范围"
              @update:value="handleDateRangeChange"
          />
        </QueryBarItem>
          </template>
        </CrudTable>

        <!-- 新增/编辑 弹窗 -->
        <CrudModal
          v-model:visible="modalVisible"
          :title="modalTitle"
          :loading="modalLoading"
          @save="handleSave"
        >
          <NForm
            ref="modalFormRef"
            label-placement="left"
            label-align="left"
            :label-width="80"
            :model="modalForm"
            :rules="validateAddUser"
          >
              <NFormItem label="消耗数量" path="nums">
                <NInputNumber
                  style="width: 100%"
                  v-model:value="modalForm.nums"
                  clearable
                  placeholder="输入消耗数量"
                  :default-value="0"
                />
              </NFormItem>
          </NForm>
        </CrudModal>
      </CommonPage>

  <!-- 业务页面 -->
</template>
